package com.hujinwen.esay.t2;

/**
 * Created by joe on 2020/5/12
 *
 * FIXME 本机计算结果和网站上的计算结果不同
 */
public class Test1 {

    public static void main(String[] args) {
        final ListNode node9 = new ListNode(9);

        // [1,9,9,9,9,9,9,9,9,9]
        final ListNode node1 = new ListNode(1);
        final ListNode node9_1 = new ListNode(9);
        final ListNode node9_2 = new ListNode(9);
        final ListNode node9_3 = new ListNode(9);
        final ListNode node9_4 = new ListNode(9);
        final ListNode node9_5 = new ListNode(9);
        final ListNode node9_6 = new ListNode(9);
        final ListNode node9_7 = new ListNode(9);
        final ListNode node9_8 = new ListNode(9);
        final ListNode node9_9 = new ListNode(9);

        node1.next = node9_1;
        node9_1.next = node9_2;
        node9_2.next = node9_3;
        node9_3.next = node9_4;
        node9_4.next = node9_5;
        node9_5.next = node9_6;
        node9_6.next = node9_7;
        node9_8.next = node9_9;


        final Solution solution = new Solution();
        final ListNode listNode = solution.addTwoNumbers(node9, node1);
        System.out.println();

    }

}

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        final int number = calculate(l1) + calculate(l2);

        ListNode resultNode = null;

        final String[] nums = Integer.toString(number).split("");
        for (int i = 0; i < nums.length; i++) {
            final int num = Integer.parseInt(nums[nums.length - i - 1]);
            if (resultNode == null) {
                resultNode = new ListNode(num);
            } else {
                ListNode lastNode = resultNode;
                while (lastNode.next != null) {
                    lastNode = lastNode.next;
                }
                lastNode.next = new ListNode(num);
            }
        }

        return resultNode;
    }

    private int calculate(ListNode node) {
        int result = 0;
        result += node.val;
        int unit = 10;
        while (node.next != null) {
            node = node.next;
            result += node.val * unit;
            unit = unit * 10;
        }
        return result;
    }
}

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}